<?php
namespace Home\Biz;

use Think\Model;

class OrderBiz {
	
	/**
	 * 查询
	 */
	public static function queryOrderByPara($thirdOrderId, $receiverMobile, $orderId, $reveiverAdd, $orderStartDate, $orderEndDate, $orderStatus, $cashBackStatus, $invoiceKind, $invoiceStatus, $consigneeName, $message, $orderType,$invoiceDate,$orderEndTime, $orderEndTimeEnd,$index = 1, $size = 20) {
		$condition_array = array ();
		if (! empty ( $thirdOrderId )) {
			$condition_array['third_order_id'] = array('like', "%".$thirdOrderId."%");
		}
	
		if (! empty ( $receiverMobile )) {
			$condition_array['consignee_cellphone'] = array('like', "%".$receiverMobile."%");
		}
	
		if (! empty ( $consigneeName )) {
			$condition_array['consignee_name'] = array('like', "%".$consigneeName."%");
		}
	
	
	
		if (! empty ( $orderType )) {
			$condition_array['order_type'] = array('eq', $orderType);
		}
	
		if (! empty ( $orderId )) {
			$condition_array['order_id'] = array('like', "%".$orderId."%");
		}
	
		if (! empty ( $reveiverAdd )) {
			$condition_array['consignee_address'] = array('like', "%".$reveiverAdd."%");
		}
	
		if (! empty ( $orderStatus )) {
			$condition_array['order_status'] = array('eq', $orderStatus);
		}
	
		if (! empty ( $orderStartDate )) {
			$condition_array['date(order_date)'] = array('egt', $orderStartDate);
		}
	
		if (! empty ( $orderEndDate )) {
			$condition_array['date(order_date)'] = array('elt', $orderEndDate);
		}
		
		if(! empty ( $orderStartDate ) && ! empty ( $orderEndDate ) ){
			$condition_array['date(order_date)'] = array('BETWEEN', array(
					$orderStartDate,
					$orderEndDate
			));
		}
			
		
		if (! empty ( $invoiceDate )) {
			$condition_array['date(invoice_date)'] = array('eq', $invoiceDate);
		}
		
		if(! empty($orderEndTime)){
			$condition_array['date(order_end_time)'] = array('egt', $orderEndTime);
		}
		
		if(! empty($orderEndTimeEnd)){
			$condition_array['date(order_end_time)'] = array('elt', $orderEndTimeEnd);
		}
		
		if(! empty($orderEndTimeEnd)&&! empty($orderEndTime)){			
			$condition_array['date(order_end_time)'] = array('BETWEEN', array(
					$orderEndTime,
					$orderEndTimeEnd
			));}
		
		
		
		if (! empty ( $cashBackStatus ) || $cashBackStatus == '0') {
			$condition_array['cash_back_status'] = array('eq', $cashBackStatus);
		}
	
		if (! empty ( $invoiceKind ) || $invoiceKind == '0') {
			$condition_array['invoice_kind'] = array('eq', $invoiceKind);
		}
	
		if (! empty ( $invoiceStatus )) {
			$condition_array['invoice_status'] = array('eq', $invoiceStatus);
		}
	
	
		if (! empty ( $message )) {
	
			if ($message == 'true') {
				// 				$condition_array['buyer_message'] = array('exp', "is not null");
				$condition_or_array = array();
				$condition_or_array['buyer_message']= array('exp', "is not null");
				$condition_or_array['seller_memo']	= array('exp', "is not null");
				$condition_array['_complex'] = $condition_or_array;
				//array_push ( $con, "(buyer_message is not null or seller_memo is not null) " );
			}
		}
	
	
		$list_order_infos = M ( 'order_info' )->field ( "`order_id`,`third_order_id`,`taobao_order_status`,`order_status`,`user_id`,`buyer_alipay_no`
       		,`buyer_name`,`buyer_nick`,`buyer_message`,`invoice_name`,`invoice_title`,`invoice_amount`,`consignee_name`,`invoice_status`
       		,`goods_amount`,`payment_amount`,`freight`,`discount_fee`,`order_amount`,`income_amount`,`order_type`,`order_date`,`cash_back_status`,`seller_memo`" )
	       		->where ( $condition_array )->order ( ' order_date desc' )->page ( $index, $size )->select ();
	       		// 总记录数
	       		$totalCount = M ( 'order_info' )->where ( $condition_array )->count ();
	
	       		// 总页数
	       		$totalPage = self::caculateTotalPage ( $totalCount, $size );
	       		// 当前页记录数
	       		$currentCount = $list_order_infos.$size;
	       		// 下一页页码
	       		$nextIndex = $index + 1;
	       		// 上一页页码 如果是第一页，页码仍然为1
	       		$preIndex = 1;
	       		if ($index > 1) {
	       			$preIndex = $index - 1;
	       		}
	
	       		$resultMap = array (
	       				'totalCount' => $totalCount,
	       				'totalPage' => $totalPage,
	       				'currentPage' => $currentCount,
	       				'nextIndex' => $nextIndex,
	       				'preIndex' => $preIndex,
	       				'index' => $index,
	       				'datas' => $list_order_infos
	       		);
	
	       		return $resultMap;
	}
	
	
	
	
	
	public static function shipDealerCashBackAmount($params_en){
		Vendor('phpExcel.PHPExcel');
		$objPHPExcel = new  \PHPExcel();
	
		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->setTitle('导出后返余额');
	
		//表头字母
		$header_letter_array = array('A','B','C','D','E','F','G','H','I','J','K');
	
		//表头设置start
		$table_header_array = array(
				'编号',
				'经销商编号',
				'经销商名称',
				'k3编码',
				'sku名称',
				'实际发货数量',
				'单价',
				'实际成交总价',
				'后返比例',
				'后返金额',
				'发货日期',
				
	
		);
		//表头设置end
	
	
		//设置表头(第一行)
		$row_index = 1;
		foreach($header_letter_array as $header_letter){
			$table_row_index = $row_index - 1;
			$objPHPExcel->getActiveSheet()->setCellValue($header_letter.strval(1),
					$table_header_array[$table_row_index]);
			$objPHPExcel->getActiveSheet()->getStyle($header_letter.strval(1))->getFont()->setBold(true);
	
			$row_index = $row_index + 1;
		}
	
	
	
		$condition_array = array();
		
		
		
		if(!empty($params_en['dealer_name'])){
			array_push($condition_array, "dl.dealer_name like '%".$params_en['dealer_name']."%'");
		}
		$start_date=$params_en['start_date'];
		if(!empty($start_date)){
			
			array_push($condition_array, "oc.send_date >= '$start_date'");
		}
		$end_date=$params_en['end_date'];
		if(!empty($end_date)){
			array_push($condition_array, "oc.send_date <= '$end_date'");
			
		}
		
		array_push($condition_array, "o.order_type = 8 AND d.qty=d.ship_qty AND s.is_rebate = 1");
		
		$condition_sql = implode(' AND ', $condition_array);
			
		$lst_rrsStockOrder_en =M('order_info')->alias('o')->
		where($condition_sql)->
		Field("dl.dealer_id,dl.dealer_name,dl.k3_code,d.sku_name,d.ship_qty,d.sale_price,d.payment_amount,dl.cash_back_rate , ROUND(d.payment_amount*dl.cash_back_rate,2) AS cash_amount  ,oc.send_date")->
		join("dealer_info  AS dl ON o.buyer_alipay_no = dl.dealer_id")->
		join("order_detail AS d ON o.order_id = d.order_id")->
		join("order_consignment AS oc ON oc.oid = d.oid")->
		join("whaley_product.sku  s ON d.sku_id = s.sku_id")->
		select();
		 
		
		// 	 return  M('')->getLastSql();
		//xls数据拼接start
		//行号，从第二行起
		$row_num = 2;
		foreach($lst_rrsStockOrder_en as $order_en){
	
			//订单类型
			$objPHPExcel->getActiveSheet()->setCellValue('A'.strval($row_num),
					$row_num-1);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('B'.strval($row_num),
					$order_en['dealer_id']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('C'.strval($row_num),
					$order_en['dealer_name']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('D'.strval($row_num),
					$order_en['k3_code']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('E'.strval($row_num),
					$order_en['sku_name']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('F'.strval($row_num),
					$order_en['ship_qty']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('G'.strval($row_num),
					$order_en['sale_price']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('H'.strval($row_num),
					$order_en['payment_amount']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('I'.strval($row_num),
					$order_en['cash_back_rate']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('J'.strval($row_num),
					$order_en['cash_amount']);
	
			
			$objPHPExcel->getActiveSheet()->setCellValue('K'.strval($row_num),
					$order_en['send_date']);
	
			
			$row_num = $row_num + 1;
		}
		//xls数据拼接end
	
		return $objPHPExcel;
	}
	
	public static function shipOrderExcelNew($params_en){
		Vendor('phpExcel.PHPExcel');
		$objPHPExcel = new  \PHPExcel();
		
		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->setTitle('导出发货单');
		
		
		//表头设置 start
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, '编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 1, '大区', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 1, '省区', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, 1, '区域', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, 1, '经销商名称', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, 1, '经销商类型', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, 1, '业务联系人', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, 1, '订单日期', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, 1, '订单编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(9, 1, '付款条件', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(10, 1, 'SKU名称', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(11, 1, '数量', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(12, 1, '单价(￥)', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(13, 1, '单台折扣', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(14, 1, '实际成交单价', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(15, 1, '实际成交总价', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(16, 1, '客户需求到货日期', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(17, 1, '收货人', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(18, 1, '收货人电话', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(19, 1, '收货地址', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(20, 1, '发货日期', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(21, 1, '备注(出货状态)', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(22, 1, '订单状态', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(23, 1, '录入人', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(24, 1, '蓝牙遥控器是否已出', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(25, 1, '内容包是否已出', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(26, 1, '送货回执是否归档', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(27, 1, '已发数量', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(28, 1, '发货状态', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(29, 1, '发货仓', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(30, 1, '余额支付金额', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(31, 1, '后返余额支付金额', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(32, 1, '产品名称', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(33, 1, '产品编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(34, 1, '产品描述', true)->getStyle()->getFont()->setBold(true);
		//表头设置 end
		
		
		
		// 搜索条件start
		$condition_array = array();
		
		if(!empty($params_en['dealer_id'])){
			array_push($condition_array, "di.dealer_id LIKE '%".$params_en['dealer_id']."%'");
		}
		
		if(!empty($params_en['dealer_name'])){
			array_push($condition_array, "di.dealer_name LIKE '%".$params_en['dealer_name']."%'");
		}
		
		if(!empty($params_en['order_id'])){
			array_push($condition_array, "op.order_id LIKE '%".$params_en['order_id']."%'");
		}
		
		
		if(!empty($params_en['order_status'])){
			array_push($condition_array, "op.order_status = ".$params_en['order_status']."");
		}
		
		if(!empty($params_en['payment_status'])){
			array_push($condition_array, "op.payment_status = ".$params_en['payment_status']."");
		}
		$start_date=$params_en['order_startdate'];
		if(!empty($start_date)){
			array_push($condition_array, "op.order_date >= '$start_date'");
		}
		$end_date=$params_en['order_enddate'];
		if(!empty($end_date)){
			array_push($condition_array, "op.order_date <= '$end_date'");
		}
		
		if($params_en['dealer_channel']== 1){
			array_push($condition_array, "op.order_type = 8");
		}
		if($params_en['dealer_channel']== 2){
			array_push($condition_array, "op.order_type = 10");
		}
		if($params_en['dealer_channel']== 3){
			array_push($condition_array, "op.order_type = 11");
		}
		// 搜索条件end
		
		//订单信息
		$condition_sql = implode(' AND ', $condition_array);
		
		
		
		$lst_rrsStockOrder_en =M('order_info')->alias('op')->
		where($condition_sql)->
		Field("op.payment_amount AS op_payment_amount ,od.ship_qty AS od_ship_qty, oc.send_date,oc.shipping_warehouse,rp.account_amount,rp.cashback_account_amount, op.* ,od.*,di.*,(SELECT COUNT(order_id) FROM order_detail WHERE order_detail.order_id= op.order_id ) AS num ")->
		join("order_payment as rp on rp.order_id = op.order_id")->
		join("order_detail od ON op.order_id = od.order_id")->
		join("order_consignment AS oc ON oc.oid = od.oid","left")->
		join("dealer_info di ON op.buyer_alipay_no = di.dealer_id","left")->
		
		select();
		
		
		$lst_sku_en = M('sku','','DB_whaley_product')->where("sku.sku_channel=8")->Field("sku.*, material_desc ")->join("product ON sku.product_id = product.product_id")->select();
		
			
			
		//xls数据拼接start
		//行号，从第二行起
		$num =0;	//明细数量
		
		$d_collect_account_amount=0;
		$d_collect_cashback_account_amount=0;
		$row_num = 2;
		
		
		foreach($lst_rrsStockOrder_en as $order_en){
			//编号
// 			$objPHPExcel->getActiveSheet()->setCellValue('A'.strval($row_num),
// 					$row_num-1);
			
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $row_num, $row_num-1, true)->getStyle()->getFont()->setBold(false);
			
			
			//大区
// 			$objPHPExcel->getActiveSheet()->setCellValue('B'.strval($row_num),
// 					$order_en['area_name']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $row_num, $order_en['area_name'], true)->getStyle()->getFont()->setBold(false);
			
			
			//省区
// 			$objPHPExcel->getActiveSheet()->setCellValue('C'.strval($row_num),
// 					$order_en['province_name']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $row_num, $order_en['province_name'], true)->getStyle()->getFont()->setBold(false);
			
			
			//区域
// 			$objPHPExcel->getActiveSheet()->setCellValue('D'.strval($row_num),
// 					$order_en['city_name']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $row_num, $order_en['city_name'], true)->getStyle()->getFont()->setBold(false);
			
			//经销商名称
// 			$objPHPExcel->getActiveSheet()->setCellValue('E'.strval($row_num),
// 					$order_en['dealer_name']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, $row_num, $order_en['dealer_name'], true)->getStyle()->getFont()->setBold(false);
				
/**
			//经销商类型
			$dealer_type 		= $order_en['dealer_type'];
			$dealer_type_text	= StringBiz::getDealerTypeRevenueStatusText($dealer_type);
			$objPHPExcel->getActiveSheet()->setCellValue('CC'.strval($row_num),
					$dealer_type_text);
				
			
			//业务联系人
			$objPHPExcel->getActiveSheet()->setCellValue('F'.strval($row_num),
					$order_en['business_leader']);
			
			//代收金额(元)(*)
			$objPHPExcel->getActiveSheet()->setCellValue('G'.strval($row_num),
					$order_en['order_date']);
			
			//收货人姓名(*)
			$objPHPExcel->getActiveSheet()->setCellValue('H'.strval($row_num),
					$order_en['order_id']);
			
			//收货人移动电话(*)
			$objPHPExcel->getActiveSheet()->setCellValue('I'.strval($row_num),
					StringBiz::getPaymentTypeText($order_en['payment_type']));
			
			//收货人固定电话(*)
			$objPHPExcel->getActiveSheet()->setCellValue('J'.strval($row_num),
					$order_en['sku_name']);
			
			//收货人所在省市区
			$objPHPExcel->getActiveSheet()->setCellValue('K'.strval($row_num),
					$order_en['qty']);
			
			$objPHPExcel->getActiveSheet()->setCellValue('L'.strval($row_num),
					$order_en['sale_price']);
			
			$objPHPExcel->getActiveSheet()->setCellValue('M'.strval($row_num),
					$order_en['discount']);
			
			//收货人详细地址(*)
			$objPHPExcel->getActiveSheet()->setCellValue('N'.strval($row_num),
					$order_en['goods_payment_amount']);
			
			//国标码
			$objPHPExcel->getActiveSheet()->setCellValue('O'.strval($row_num),
					$order_en['payment_amount']);
			
			//预约送货时间
			$objPHPExcel->getActiveSheet()->setCellValue('P'.strval($row_num),
					'');
			
			//预约到货时间
			$objPHPExcel->getActiveSheet()->setCellValue('Q'.strval($row_num),
					$order_en['consignee_name']);
			
			//客户物料号(*)-----
			$objPHPExcel->getActiveSheet()->setCellValue('R'.strval($row_num),
					$order_en['consignee_cellphone']);
			
			//订单数量(*)
			$objPHPExcel->getActiveSheet()->setCellValue('S'.strval($row_num),
					$order_en['consignee_province'].$order_en['consignee_city'].$order_en['consignee_district'].$order_en['consignee_address']);
			
			//发货日期
			$objPHPExcel->getActiveSheet()->setCellValue('T'.strval($row_num),
					$order_en['send_date']);
			
			//发货仓库(*)
			$objPHPExcel->getActiveSheet()->setCellValue('U'.strval($row_num),
					$order_en['order_remark']);
			
				
				
			$objPHPExcel->getActiveSheet()->setCellValue('V'.strval($row_num),
					StringBiz::getPromoterOrderStatusText($order_en['order_status']));
				
			//货主
			$objPHPExcel->getActiveSheet()->setCellValue('W'.strval($row_num),
					$order_en['seller_name']);
				
			
				
			//收货仓库
			$objPHPExcel->getActiveSheet()->setCellValue('X'.strval($row_num),
					'');
			
			//货主
			$objPHPExcel->getActiveSheet()->setCellValue('Y'.strval($row_num),
					'');
			
			//服务方式
			$objPHPExcel->getActiveSheet()->setCellValue('Z'.strval($row_num),
					'');
			
			if($order_en['od_ship_qty']==null || empty($order_en['od_ship_qty'] )|| $order_en['od_ship_qty'] ==0 ){
				$objPHPExcel->getActiveSheet()->setCellValue('AA'.strval($row_num),
						0);
			}else{
				$objPHPExcel->getActiveSheet()->setCellValue('AA'.strval($row_num),
						$order_en['od_ship_qty']);
			}
				
			if($order_en['od_ship_qty']==null || empty($order_en['od_ship_qty']) || $order_en['od_ship_qty'] ==0 ){
				$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
						'未发货');
			}else{
			
				if(($order_en['od_ship_qty'] > 0)  && ($order_en['od_ship_qty'] < $order_en['qty'])){
					$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
							'部分发货');
				}else if($order_en['od_ship_qty'] == $order_en['qty']){
						
					$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
							'全部发货');
				}else{
						
					$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
							'不正确的发货数量,请检查！'.$order_en['qty']);
				}
			
			
			}
			//发货仓
			$objPHPExcel->getActiveSheet()->setCellValue('AC'.strval($row_num),
					$order_en['shipping_warehouse']);
			//计算余额分摊后返余额分摊
			$total= $order_en['num'];
			if($total==1){
				//只有一个订单明细,直接赋值分摊
				$objPHPExcel->getActiveSheet()->setCellValue('AD'.strval($row_num),
						$order_en['account_amount']);
				$objPHPExcel->getActiveSheet()->setCellValue('AE'.strval($row_num),
						$order_en['cashback_account_amount']);
				//处理一个完整的订单明细,以下变量清零
				$num=0;
				$d_collect_account_amount=0;
				$d_collect_cashback_account_amount=0;
			}else{
				//多个订单明细
				if($num == $total-1){
					//订单最后一条明细做减法
					 
					 
					$objPHPExcel->getActiveSheet()->setCellValue('AD'.strval($row_num),
							$order_en['account_amount']-$d_collect_account_amount);
					$objPHPExcel->getActiveSheet()->setCellValue('AE'.strval($row_num),
							$order_en['cashback_account_amount']-$d_cashback_account_amount);
			
					//处理一个完整的订单明细,以下变量清零
					$num=0;
					$d_collect_account_amount=0;
					$d_collect_cashback_account_amount=0;
				}
			
				$d_account_amount=round($order_en['payment_amount']*$order_en['account_amount']/$order_en['op_payment_amount'],2);
				$d_cashback_account_amount=round($order_en['payment_amount']*$order_en['cashback_account_amount']/$order_en['op_payment_amount'],2);
				$objPHPExcel->getActiveSheet()->setCellValue('AD'.strval($row_num),
						$d_account_amount);
				$objPHPExcel->getActiveSheet()->setCellValue('AE'.strval($row_num),
						$d_cashback_account_amount);
				//分别累计N-1条订单明细的余额，后返余额总额
				$d_collect_account_amount+=$d_account_amount;
				$d_collect_cashback_account_amount+=$d_cashback_account_amount;
				$num +=1;
			}
			
			$curr_sku_id = $order_en['sku_id'];
			$lst_filter_sku= array_filter($lst_sku_en,function ($item) use ($curr_sku_id){
				return $item['sku_id'] == $curr_sku_id;
			});
			$curr_sku_en = current($lst_filter_sku);
					
			$objPHPExcel->getActiveSheet()->setCellValue('AF'.strval($row_num),
						$curr_sku_en['product_name']);
			$objPHPExcel->getActiveSheet()->setCellValue('AG'.strval($row_num),
						$curr_sku_en['material_no']);
			$objPHPExcel->getActiveSheet()->setCellValue('AH'.strval($row_num),
						$curr_sku_en['material_desc']);
			**/
			$row_num = $row_num + 1;
		}
		return $objPHPExcel;
		
	}
	
	
	
	
	
	
	
	
	public static function shipOrderExcel($params_en){
		Vendor('phpExcel.PHPExcel');
		$objPHPExcel = new  \PHPExcel();

		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->setTitle('导出发货单');

		//表头字母
		$header_letter_array = array('A','B','C','D','E', 'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH', 'AI','AJ','AK','AL');

		//表头设置start
		$table_header_array = array(
			'编号',
			'大区',
			'省区',
			'区域',
			'经销商名称',
			'业务联系人',
			'订单日期',
			'订单编号',
			'付款条件',
			'SKU名称',
			'数量',
			'单价(￥)',
			'单台折扣',
			'实际成交单价',
			'实际成交总价',
			'客户需求到货日期',
			'收货人',
			'收货人电话',
			'收货地址',
			'发货日期',
			'备注(出货状态)',
			'订单状态',
			'录入人',
			'蓝牙遥控器是否已出',
			'内容包是否已出',
			'送货回执是否归档',
			'已发数量',
			'发货状态',
			'发货仓'	,
			'余额支付金额',	
			'后返余额支付金额',
			'产品名称',
			'产品编号',
			'产品描述',
            '经销商类型',
			'收货人省名称',
			'收货人市名称',
			'收货人区名称'
		);
		//表头设置end


		//设置表头(第一行)
		$row_index = 1;
		foreach($header_letter_array as $header_letter){
			$table_row_index = $row_index - 1;
			$objPHPExcel->getActiveSheet()->setCellValue($header_letter.strval(1),
				$table_header_array[$table_row_index]);
			$objPHPExcel->getActiveSheet()->getStyle($header_letter.strval(1))->getFont()->setBold(true);

			$row_index = $row_index + 1;
		}



		// 搜索条件start
		$condition_array = array();

		if(!empty($params_en['dealer_id'])){
			array_push($condition_array, "di.dealer_id LIKE '%".$params_en['dealer_id']."%'");
		}

		if(!empty($params_en['dealer_name'])){
			array_push($condition_array, "di.dealer_name LIKE '%".$params_en['dealer_name']."%'");
		}

		if(!empty($params_en['order_id'])){
			array_push($condition_array, "op.order_id LIKE '%".$params_en['order_id']."%'");
		}


		if(!empty($params_en['order_status'])){
			array_push($condition_array, "op.order_status = ".$params_en['order_status']."");
		}

		if(!empty($params_en['payment_status'])){
			array_push($condition_array, "op.payment_status = ".$params_en['payment_status']."");
		}
		$start_date=$params_en['order_startdate'];
		if(!empty($start_date)){
			array_push($condition_array, "op.order_date >= '$start_date'");
		}
		$end_date=$params_en['order_enddate'];
		if(!empty($end_date)){
			array_push($condition_array, "op.order_date <= '$end_date'");
		}
		
		if($params_en['dealer_channel']== 1){
			array_push($condition_array, "op.order_type = 8");
		}
		if($params_en['dealer_channel']== 2){
			array_push($condition_array, "op.order_type = 10");
		}
		if($params_en['dealer_channel']== 3){
			array_push($condition_array, "op.order_type = 11");
		}
		// 搜索条件end

		$user_id = cookie('login_user_id');
		$sale_en= M('sale_user')->where("sale_name='%s'",$user_id)->find();
		
		
		if($sale_en!=null){
			
			$sale_name_join=M('sale_user')->field("GROUP_CONCAT(sale_name) as sale_name_join")->where(" FIND_IN_SET(sale_id, getSubSaleList('%s'))",$sale_en['sale_id'])->find();
			$sale_name_lst=$sale_name_join['sale_name_join'];
			$no_businness=" and FIND_IN_SET(o.seller_alipay_no,'$sale_name_lst')";
			array_push($condition_array, "FIND_IN_SET(op.seller_alipay_no,'$sale_name_lst')");
		}
		
		
		//订单信息
		$condition_sql = implode(' AND ', $condition_array);



		$lst_rrsStockOrder_en =M('order_info')->alias('op')->
		where($condition_sql)->
		Field("op.payment_amount AS op_payment_amount , rp.account_amount as op_account_amount, rp.cashback_account_amount as op_cashback_account_amount,od.ship_qty AS od_ship_qty,od.rma_qty AS od_rma_qty, oc.send_date,oc.shipping_warehouse,rp.account_amount,rp.cashback_account_amount, op.* ,od.*,di.*")->
		join("order_payment as rp on rp.order_id = op.order_id")->
		join("order_detail od ON op.order_id = od.order_id")->
		join("order_consignment AS oc ON oc.oid = od.oid","left")->
		join("dealer_info di ON op.buyer_alipay_no = di.dealer_id","left")->
		
		select();
		
		
		$lst_sku_en = M('sku','','DB_whaley_product')->where("sku.sku_channel=8")->Field("sku.*, material_desc ")->join("product ON sku.product_id = product.product_id")->select();
		
 	 
 	 
		//xls数据拼接start
		//行号，从第二行起
		$num =0;	//明细数量

		$d_collect_account_amount=0;
		$d_collect_cashback_account_amount=0;
		$row_num = 2;
		foreach($lst_rrsStockOrder_en as $order_en){

			//编号
			$objPHPExcel->getActiveSheet()->setCellValue('A'.strval($row_num),
				$row_num-1);

			//大区
			$objPHPExcel->getActiveSheet()->setCellValue('B'.strval($row_num),
				$order_en['area_name']);

			//省区
			$objPHPExcel->getActiveSheet()->setCellValue('C'.strval($row_num),
				$order_en['province_name']);

			//区域
			$objPHPExcel->getActiveSheet()->setCellValue('D'.strval($row_num),
				$order_en['city_name']);

			//经销商名称
			$objPHPExcel->getActiveSheet()->setCellValue('E'.strval($row_num),
				$order_en['dealer_name']);
			
			
			

			

			//业务联系人
			$objPHPExcel->getActiveSheet()->setCellValue('F'.strval($row_num),
				$order_en['business_leader']);

			//代收金额(元)(*)
			$objPHPExcel->getActiveSheet()->setCellValue('G'.strval($row_num),
				$order_en['order_date']);

			//收货人姓名(*)
			$objPHPExcel->getActiveSheet()->setCellValue('H'.strval($row_num),
				$order_en['order_id']);

			//收货人移动电话(*)
			$objPHPExcel->getActiveSheet()->setCellValue('I'.strval($row_num),
				StringBiz::getPaymentTypeText($order_en['payment_type']));

			//收货人固定电话(*)
			$objPHPExcel->getActiveSheet()->setCellValue('J'.strval($row_num),
				$order_en['sku_name']);

			//收货人所在省市区
			$objPHPExcel->getActiveSheet()->setCellValue('K'.strval($row_num),
				$order_en['qty']);

			$objPHPExcel->getActiveSheet()->setCellValue('L'.strval($row_num),
				$order_en['sale_price']);

			$objPHPExcel->getActiveSheet()->setCellValue('M'.strval($row_num),
				$order_en['discount']);

			//收货人详细地址(*)
			$objPHPExcel->getActiveSheet()->setCellValue('N'.strval($row_num),
				$order_en['goods_payment_amount']);

			//国标码
			$objPHPExcel->getActiveSheet()->setCellValue('O'.strval($row_num),
				$order_en['payment_amount']);

			//预约送货时间
			$objPHPExcel->getActiveSheet()->setCellValue('P'.strval($row_num),
				'');

			//预约到货时间
			$objPHPExcel->getActiveSheet()->setCellValue('Q'.strval($row_num),
				$order_en['consignee_name']);

			//客户物料号(*)-----
			$objPHPExcel->getActiveSheet()->setCellValue('R'.strval($row_num),
				$order_en['consignee_cellphone']);

			//订单数量(*)
			$objPHPExcel->getActiveSheet()->setCellValue('S'.strval($row_num),
				$order_en['consignee_province'].$order_en['consignee_city'].$order_en['consignee_district'].$order_en['consignee_address']);

			//发货日期
			$objPHPExcel->getActiveSheet()->setCellValue('T'.strval($row_num),
				$order_en['send_date']);

			//发货仓库(*)
			$objPHPExcel->getActiveSheet()->setCellValue('U'.strval($row_num),
				$order_en['order_remark']);

			
			
			$objPHPExcel->getActiveSheet()->setCellValue('V'.strval($row_num),
					StringBiz::getPromoterOrderStatusText($order_en['order_status']));
			
			//货主
			$objPHPExcel->getActiveSheet()->setCellValue('W'.strval($row_num),
					$order_en['seller_name']);
			
						
			
			//收货仓库
			$objPHPExcel->getActiveSheet()->setCellValue('X'.strval($row_num),
				'');

			//货主
			$objPHPExcel->getActiveSheet()->setCellValue('Y'.strval($row_num),
				'');

			//服务方式
			$objPHPExcel->getActiveSheet()->setCellValue('Z'.strval($row_num),
				'');
            
			if($order_en['od_ship_qty']==null || empty($order_en['od_ship_qty'] )|| $order_en['od_ship_qty'] ==0 ){
				$objPHPExcel->getActiveSheet()->setCellValue('AA'.strval($row_num),
						0);
			}else{
				$objPHPExcel->getActiveSheet()->setCellValue('AA'.strval($row_num),
						$order_en['od_ship_qty']);
			}
			
			if( $order_en['od_ship_qty'] ==0 && $order_en['od_rma_qty']== 0 ){
				$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
						'未发货');
			}else if($order_en['od_ship_qty'] ==0 && ($order_en['od_rma_qty']== $order_en['qty'])){
				
				$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
						'未发货，已取消');
			}else{
				
				if(($order_en['od_ship_qty'] > 0)  && ($order_en['od_ship_qty'] < $order_en['qty'])){
					$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
							'部分发货');
				}else if($order_en['od_ship_qty'] == $order_en['qty']){
					
					$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
							'全部发货');
				}else{
					
					$objPHPExcel->getActiveSheet()->setCellValue('AB'.strval($row_num),
							'不正确的发货数量,请检查！'.$order_en['qty']);
				}
				
				
			}
			//发货仓
			$objPHPExcel->getActiveSheet()->setCellValue('AC'.strval($row_num),
					$order_en['shipping_warehouse']);
			
			$objPHPExcel->getActiveSheet()->setCellValue('AD'.strval($row_num),
					$order_en['account_amount']);
			$objPHPExcel->getActiveSheet()->setCellValue('AE'.strval($row_num),
					$order_en['cashback_account_amount']);
		/*  //计算余额分摊后返余额分摊
			$total= $order_en['num'];
			if($total==1){
				//只有一个订单明细,直接赋值分摊
				$objPHPExcel->getActiveSheet()->setCellValue('AD'.strval($row_num),
						$order_en['account_amount']);
				$objPHPExcel->getActiveSheet()->setCellValue('AE'.strval($row_num),
						$order_en['cashback_account_amount']);
			    //处理一个完整的订单明细,以下变量清零	
				$num=0;
				$d_collect_account_amount=0;
				$d_collect_cashback_account_amount=0;
			}else{
				//多个订单明细
			   if($num == $total-1){
			   	//订单最后一条明细做减法
			   	
			   	
			   	$objPHPExcel->getActiveSheet()->setCellValue('AD'.strval($row_num),
			   			$order_en['account_amount']-$d_collect_account_amount);
			   	$objPHPExcel->getActiveSheet()->setCellValue('AE'.strval($row_num),
			   			$order_en['cashback_account_amount']-$d_cashback_account_amount);
	
			   	//处理一个完整的订单明细,以下变量清零
			   	$num=0;
			   	$d_collect_account_amount=0;
			   	$d_collect_cashback_account_amount=0;
			   }
	
			   $d_account_amount=round($order_en['payment_amount']*$order_en['account_amount']/$order_en['op_payment_amount'],2);
			   $d_cashback_account_amount=round($order_en['payment_amount']*$order_en['cashback_account_amount']/$order_en['op_payment_amount'],2);
			   $objPHPExcel->getActiveSheet()->setCellValue('AD'.strval($row_num),
			   		$d_account_amount);
			   $objPHPExcel->getActiveSheet()->setCellValue('AE'.strval($row_num),
			   		$d_cashback_account_amount);				
			   //分别累计N-1条订单明细的余额，后返余额总额
			   $d_collect_account_amount+=$d_account_amount;
			   $d_collect_cashback_account_amount+=$d_cashback_account_amount;
			   $num +=1;
			}
		  */
		     $curr_sku_id = $order_en['sku_id'];
		     $lst_filter_sku= array_filter($lst_sku_en,function ($item) use ($curr_sku_id){
		     	return $item['sku_id'] == $curr_sku_id;
		     });
			$curr_sku_en = current($lst_filter_sku);
			
			$objPHPExcel->getActiveSheet()->setCellValue('AF'.strval($row_num),
					$curr_sku_en['product_name']);
			$objPHPExcel->getActiveSheet()->setCellValue('AG'.strval($row_num),
					$curr_sku_en['material_no']);
			$objPHPExcel->getActiveSheet()->setCellValue('AH'.strval($row_num),
					$curr_sku_en['material_desc']);


            //经销商类型
            $dealer_type 		= $order_en['dealer_type'];
            $dealer_type_text	= StringBiz::getDealerTypeRevenueStatusText($dealer_type);
            $objPHPExcel->getActiveSheet()->setCellValue('AI'.strval($row_num),
                $dealer_type_text);

            $objPHPExcel->getActiveSheet()->setCellValue('AJ'.strval($row_num),
            		$order_en['consignee_province']);
            $objPHPExcel->getActiveSheet()->setCellValue('AK'.strval($row_num),
            		$order_en['consignee_city']);
            $objPHPExcel->getActiveSheet()->setCellValue('AL'.strval($row_num),
            		$order_en['consignee_district']);
            
            
            
            
            
			$row_num = $row_num + 1;
		}
		//xls数据拼接end

		return $objPHPExcel;
	}
	public static function getSendWarehouse($district_id){
		$rrsShippingRegion_en = M('rrsShippingRegion', '', 'DB_whaley_trade')
			->where(array('recive_district_id'=>$district_id))
			->find();

		if(empty($rrsShippingRegion_en)){
			return '';
		}
		return $rrsShippingRegion_en['warehouse_name'];
	}
	public static function OrderExportExcel($con){
		Vendor('phpExcel.PHPExcel');
		$objPHPExcel = new  \PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->setTitle('导入');
		//表头字母
		$header_letter_array = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q');
		//表头设置start
		$table_header_array = array(
				'订单编号',
				'第三方订单编号',
				'卖家支付宝账号',
				'款式编号',
				'款式名称',
				'单价(元)',
				'购买数量',
				'实付金额',
				'订单状态',
				'订单时间',
				'支付时间',
				'订单发货的快递公司名称',
				'物流单号',
				'发货时间',
				'发票形式',
				'第三方发票抬头',
				'日日顺出库单号'
		);
		//表头设置end
		//设置表头(第一行)
		$row_index = 1;
		foreach($header_letter_array as $header_letter){
			$table_row_index = $row_index - 1;
			$objPHPExcel->getActiveSheet()->setCellValue($header_letter.strval(1),
					$table_header_array[$table_row_index]);
			$objPHPExcel->getActiveSheet()->getStyle($header_letter.strval(1))->getFont()->setBold(true);
			$row_index = $row_index + 1;
		}
		//订单信息
		$condition_sql = implode(' AND ', $con);
		$sql = "
			SELECT o.order_id, o.third_order_id, o.`seller_alipay_no`, od.`style_id`, od.`style_name`,
				od.`sale_price`,od.qty,od.`payment_amount`,o.`order_status`,o.`order_date`,
				op.payment_date,od.`logistics_company`, od.`logistics_no`,'' AS 'send_date', o.`invoice_kind`, o.`invoice_name`,
				rso.`rrs_stock_order_id`
			FROM order_info o
				INNER JOIN order_detail od ON o.order_id = od.order_id
				INNER JOIN order_payment op ON o.`order_id` = op.order_id
				LEFT JOIN rrs_stock_order rso ON od.`third_oid` = rso.`third_oid` ";
		if(!empty($con)){
			$sql = $sql." WHERE ".$condition_sql." ORDER BY order_date DESC";
		}else{
			$sql = $sql." ORDER BY order_date DESC";
		}
		$lst_rrsStockOrder_en = M('', '', 'DB_whaley_trade')->query($sql);
		
		//xls数据拼接start
		//行号，从第二行起
		$row_num = 2;
		foreach($lst_rrsStockOrder_en as $order_en){
			//订单编号
			$objPHPExcel->getActiveSheet()->setCellValue('A'.strval($row_num),
					$order_en['order_id']);
			
			$objPHPExcel->getActiveSheet()->setCellValue('B'.strval($row_num),
					' '.$order_en['third_order_id']);
			//卖家支付宝账号
			$objPHPExcel->getActiveSheet()->setCellValue('C'.strval($row_num),
					$order_en['seller_alipay_no']);
			//款式编号
			$objPHPExcel->getActiveSheet()->setCellValue('D'.strval($row_num),
					$order_en['style_id']);
			//款式名称
			$objPHPExcel->getActiveSheet()->setCellValue('E'.strval($row_num),
					$order_en['style_name']);
			//单价(元)
			$objPHPExcel->getActiveSheet()->setCellValue('F'.strval($row_num),
					$order_en['sale_price']);
			//购买数量
			$objPHPExcel->getActiveSheet()->setCellValue('G'.strval($row_num),
					$order_en['qty']);
			//实付金额
			$objPHPExcel->getActiveSheet()->setCellValue('H'.strval($row_num),
					$order_en['payment_amount']);
			//订单状态
			$objPHPExcel->getActiveSheet()->setCellValue('I'.strval($row_num),
					CommonBiz::changeWhaleyOrderStatus($order_en['order_status']));
			//订单时间
			$objPHPExcel->getActiveSheet()->setCellValue('J'.strval($row_num),
					$order_en['order_date']);
			//支付时间
			$objPHPExcel->getActiveSheet()->setCellValue('K'.strval($row_num),
					$order_en['payment_date']);
			//订单发货的快递公司名称
			$objPHPExcel->getActiveSheet()->setCellValue('L'.strval($row_num),
					$order_en['logistics_company']);
			//物流单号
			$objPHPExcel->getActiveSheet()->setCellValue('M'.strval($row_num),
					$order_en['logistics_no']);
			//发货时间
			$objPHPExcel->getActiveSheet()->setCellValue('N'.strval($row_num),
					$order_en['send_date']);
			//发票形式
			$objPHPExcel->getActiveSheet()->setCellValue('O'.strval($row_num),
					CommonBiz::changeInvoiceKind($order_en['invoice_kind']));
			//第三方发票抬头
			$objPHPExcel->getActiveSheet()->setCellValue('P'.strval($row_num),
					$order_en['invoice_name']);
			//日日顺出库单号
			$objPHPExcel->getActiveSheet()->setCellValue('Q'.strval($row_num),
					$order_en['rrs_stock_order_id']);
			
			$row_num = $row_num + 1;
		}
		//xls数据拼接end
		return $objPHPExcel;
	}
	
	
	public static function caculateTotalPage($totalCount,$pageSize){
		
		$count = intval($totalCount / $pageSize);
		
		$countLeft = $totalCount % $pageSize;
		
		if($countLeft !=0){
			$count = $count+1;
		}
		
		return $count;
	}
	
	public static function rebuildRedInvoiceItem($invoice_item_reds,$dicountfee,$max_invoice_amount){
		
		
		$rebuild_invoice_items = array();
		
		foreach ($invoice_item_reds as $invoice_item_red){
			
			if($invoice_item_red['invoice_amount'] == $max_invoice_amount){
				
				$invoice_amount = $invoice_item_red['invoice_amount']  - $dicountfee  ;
				//减去会员包之后算出来不含税价格
				$invoice_item_red['sum_price'] = self::chargeTaxByRate($invoice_amount, $invoice_item_red['tax_rate']) ;
				//不含会员包的税额
				$invoice_item_red['tax'] =$invoice_amount - $invoice_item_red['sum_price'];
					
				$invoice_item_red['invoice_amount'] =  $invoice_amount;
				
				$invoice_item_red['amount'] = $invoice_amount/$invoice_item_red['quantity'];
				//price是不含税价格
				
				$invoice_item_red['price'] = self::chargePriceByRate($invoice_amount/$invoice_item_red['quantity'],
						$invoice_item_red['tax_rate']) ;
				
				array_push($rebuild_invoice_items, $invoice_item_red);
				
			}else{
				array_push($rebuild_invoice_items, $invoice_item_red);
			}
		}
		
		return $rebuild_invoice_items;
		
	}
	
	public static function redInvoiceBiz($orderId,$redReason){
		
		
		//选查询目前有效的invoice 与  invoice item
		$order_invoice_diable = M('order_invoice')->where("order_id='$orderId' AND status = 1")->find();
		
		$diable_invoice_serial =  $order_invoice_diable['invoice_serial_no'];
		
		$lst_order_invoice_en_item_disable = M('order_invoice_item')->where("invoice_serial_no='$diable_invoice_serial'")->select();
		
		$invoice_item_reds = array();
		
		//获取新的serialno
		$invoice_serial_no_red = CommonBiz::getInvoiceSeq();
		
		$dicountfee = 0.0;
		
		$max_invoice_amount = 0.0;
		foreach ($lst_order_invoice_en_item_disable as $disable_invoice_item){
			
			if($disable_invoice_item['invoice_amount']>0){
				
				//包装电视机 发票明细信息
				$dataTv['invoice_serial_no'] =$invoice_serial_no_red;
				
				$dataTv['order_id'] = $disable_invoice_item['order_id'];
				
				$dataTv['third_order_id'] = $disable_invoice_item['third_order_id'];
					
				$dataTv['tax_rate'] = $disable_invoice_item['tax_rate'];
					
				$dataTv['item_name'] =$disable_invoice_item['item_name'];
				
				$dataTv['invoice_date'] = date("y-m-d H:i:s", time());
				
				//减去会员包之后算出来不含税价格
				$dataTv['sum_price'] = 0-$disable_invoice_item['sum_price'] ;
				//不含会员包的税额
				$dataTv['tax'] = 0 - $disable_invoice_item['tax'];
					
				$dataTv['invoice_amount'] =  0 - $disable_invoice_item['invoice_amount'];
				
				if($dataTv['invoice_amount'] < $max_invoice_amount) {
					$max_invoice_amount = $dataTv['invoice_amount'];
				}
				
					
				$dataTv['row_type'] = 0;
				
				$dataTv['item_no'] = $disable_invoice_item['item_no'];
				//price是不含税价格
				$dataTv['price'] = $disable_invoice_item['price'];
				
				$dataTv['amount'] =$disable_invoice_item['amount'];
				
				$dataTv['quantity'] =  0-$disable_invoice_item['quantity'];
				
				$dataTv['unit']= $disable_invoice_item['unit'];
					
				$dataTv['specification']= $disable_invoice_item['specification'];
					
				array_push($invoice_item_reds, $dataTv);
				
			}else{
				//将折扣保存起来
				$dicountfee = $disable_invoice_item['invoice_amount'];
			}
		}
		
		
		//如果存在折扣的话，进行rebuild
		if($dicountfee!= 0.0){
			$invoice_item_reds = self::rebuildRedInvoiceItem($invoice_item_reds,$dicountfee,$max_invoice_amount);
		}
		
		
		$Model = new Model();
		$today = date("y-m-d H:i:s", time());
		
		if($redReason =='2'){
			$Model->execute("update order_info set invoice_kind = 0 where order_id ='$orderId'");
		}else if($redReason=='3'){
			$Model->execute("update order_info set invoice_kind = 22 where order_id ='$orderId'");
		} 
		
		$Model->execute("update order_info set red_flag = 1,invoice_date='$today',invoice_status = 2 where order_id ='$orderId'");
		$Model->execute("update order_invoice set status = 0,red_flag = 1 where order_id ='$orderId'");
		
		$totoalFee  = self::getTotalTaxSumPrice($invoice_item_reds);
		
		$data['invoice_serial_no'] =$invoice_serial_no_red;
		$data['order_id'] = $order_invoice_diable['order_id'];
		$data['third_order_id'] = $order_invoice_diable['third_order_id'];
		$data['invoice_name'] = $order_invoice_diable['invoice_name'];
		$data['invoice_kind'] =21;
		$data['invoice_status'] = 2;
		$data['invoice_date'] = date("y-m-d H:i:s", time());
		$data['invoice_amount'] = 0 -$order_invoice_diable['invoice_amount'];
		
		
		$data['sum_price'] =$totoalFee['totalPrice'];
		$data['sum_tax'] =  $totoalFee['totalTax'];
		$data['platform_code'] = $order_invoice_diable['platform_code'];
		$data['platform_tid'] = $order_invoice_diable['platform_tid'];
		$data['status'] = 1;
		$data['invoice_type'] = 'red';
		$data['blue_serial_no'] = $diable_invoice_serial;
		$data['red_flag'] = 1;
		$data['red_reason'] = $redReason;
		
		//保存新的invoice
		M('order_invoice')->data($data)->add();
		
		//写入invoice_item
		foreach($invoice_item_reds as $invoice_item_en){
			M('order_invoice_item')->add($invoice_item_en);
		}
		
		
	}
	
	
	public static function queryUpdateInvoiceNameByPara($thirdOrderIds){
		$Model = new Model();
		$sql_query = "SELECT oi.* FROM order_info oi WHERE  1=1 ";
		$sql_query = $sql_query. " AND oi.third_order_id ='$thirdOrderIds' " ;
		$list_order_infos = $Model->query($sql_query);
		$resultMap = array('datas'=>$list_order_infos);
		return $resultMap;
	}
	
	public static function queryInvoiceByPara($thirdOrderIds, $orderStartDate, $orderEndDate,$cashBackStatus,$message,$orderType,
			$index = 1, $size = 100) {
		
				
				$Model = new Model();
				
				//LEFT JOIN order_detail od ON oi.third_order_id = od.third_order_id
				
				$sql_query = "SELECT oi.* FROM order_info oi WHERE  oi.invoice_status =1 AND oi.order_date > '2016-05-09 10:30:00' AND oi.invoice_kind =21 AND oi.order_status = 35 ";

				//AND od.third_sku_id IN ('3104357627810','3116776067094','3142548481809')
		
				//LEFT JOIN order_detail od ON oi.third_order_id = od.third_order_id
				
				$MinInvoiceAmt = C('InvoiceConfig.MinOrderAmount');
				
				$sql_count = "SELECT count(*) as 'totalcount' FROM order_info oi WHERE  oi.invoice_status =1 AND oi.order_date > '2016-05-09 10:30:00' AND oi.invoice_kind =21 AND oi.order_status = 35 ";
				
				//AND od.third_sku_id IN ('3104357627810','3116776067094','3142548481809') 
				
				if(!empty($thirdOrderIds)){
					
					
					$thirdOrderIds = rtrim($thirdOrderIds,',');
					$thirdOrderIds = rtrim($thirdOrderIds,'，');
					
					
					$thirdOrderIds =  str_replace(",","','",$thirdOrderIds);
					$thirdOrderIds =  str_replace("，","','",$thirdOrderIds);
					
					
					$sql_query = $sql_query. " AND oi.third_order_id in ('$thirdOrderIds') " ;
					
					$sql_count =$sql_count." AND oi.third_order_id in ('$thirdOrderIds') " ;
				}
				

				if(!empty($orderType)){
					$sql_query = $sql_query. " AND oi.order_type =$orderType " ;
					$sql_count = $sql_count. " AND oi.order_type =$orderType " ;
				}
				
				if(!empty($message)){
				
					if(	$message=='true'){
						
						
						$sql_query = $sql_query. " AND (oi.buyer_message is not null or oi.seller_memo is not null) " ;
						
						$sql_count =$sql_count." AND (oi.buyer_message is not null or oi.seller_memo is not null) " ;
						
					}
				}
				
				if(!empty($cashBackStatus) || $cashBackStatus=='0'){
					
					$sql_query = $sql_query. " AND oi.cash_back_status = '$cashBackStatus'" ;
						
					$sql_count =$sql_count." AND oi.cash_back_status = '$cashBackStatus'" ;
				}
				
				if(!empty($orderStartDate)){
					
					$sql_query = $sql_query."AND  date(oi.order_date) >= '$orderStartDate'" ;
					
					$sql_count = $sql_count."AND  date(oi.order_date) >= '$orderStartDate'" ;
				}
	
				if(!empty($orderEndDate)){
					
					$sql_query = $sql_query."AND  date(oi.order_date) <= '$orderStartDate' " ;
					
					$sql_count =$sql_count."AND  date(oi.order_date) <= '$orderStartDate' " ;
						
				}
				
				$limit_index = ($index -1) * $size;
				
				$sql_query = $sql_query." order by oi.order_date desc limit $limit_index , $size";
				
	
				$list_order_infos = $Model->query($sql_query);
				
	
	       		//总记录数
	       		$totalCounts = $Model->query($sql_count);
	       		$totalCount = $totalCounts[0]['totalcount'];

	       		//总页数
	       		$totalPage = self::caculateTotalPage($totalCount,$size);
	       		//当前页记录数
	       		$currentCount = $list_order_infos.$size;
	       		//下一页页码
	       		$nextIndex = $index +1 ;
	       		//上一页页码 如果是第一页，页码仍然为1
	       		$preIndex = 1;
	       		if($index >1){
	       			$preIndex = $index -1 ;
	       		}
	
	       		$resultMap = array('totalCount'=>$totalCount,
	       				'totalPage'=>$totalPage,
	       				'currentPage'=>$currentCount,
	       				'nextIndex'=>$nextIndex,
	       				'preIndex'=>$preIndex,
	       				'index'=>$index,
	       				'datas'=>$list_order_infos
	       		);
	
	       		return $resultMap;
	}
	
	
	public static function UpdateOrderInfoInvoiceStatus($orderIds, $invoice_type) {
		
		$array_order_ids=explode(",",$orderIds);
		$Model = new Model();
		
		if($invoice_type =='21'){
			foreach ($array_order_ids as $value){
				$today = date("y-m-d H:i:s", time());
				
				$Model->execute("update order_info set invoice_status = 2 , invoice_date='$today', invoice_kind='$invoice_type'
						where order_id ='$value'");
			}
		}else{
			foreach ($array_order_ids as $value){
				$Model->execute("update order_info set invoice_status = 4, invoice_date='$today' , invoice_kind='$invoice_type'
						where order_id ='$value'");
			}
		}
		

	}
	

	public static function UpdateOrderInfoInvoiceTitle($thirdOrderId, $invoice_title) {
	
		$Model = new Model();
	    $Model->execute("update order_info set invoice_title = '$invoice_title'
						where order_id ='$thirdOrderId'");
	
	}
	
	public static function UpdateOrderInfoInvoiceAddress($thirdOrderId, $invoice_address) {
		echo $thirdOrderId.$invoice_address;
		$Model = new Model();
		$Model->execute("update order_info set invoice_address = '$invoice_address'
				where third_order_id ='$thirdOrderId'");
	}
	
	public static function UpdateOrderStatus($order_id, $order_status, $user) {
		$Model = new Model();
		$order_info=M('order_info')->where("order_id='$order_id'")->find();
		if(empty($order_info)){
			return "订单不存在";
		}
		$err_msg = '';
		switch($order_status){
			case 31://已发货
				if($order_info['order_status'] != 22){
					$err_msg = '未支付完成，不允许发货';
				}
				break;
			default:
				$err_msg = "不支持更改的订单状态";
				break;
		}
		
		if(!empty($err_msg)){
			return $err_msg;
		}
		//更改订单状态
		M('order_info')->where("order_id='$order_id'")->setField('order_status', $order_status);
		
		//增加订单状态log变更日志
		$data['order_id'] = $order_id ;
		$data['order_status'] = $order_status;
		$data['order_status_text'] = StringBiz::getPromoterOrderStatusText($order_status);
		$data['create_date'] = date("y-m-d H:i:s", time());
		$data['create_user'] = $user;
		M('order_status_change_log')->data($data)->add();
		
	}
	/**
	 * Description: 获取订单的支付信息 并计算发票总金额
	 * @version 2016年12月15日 下午8:30:08 
	 * @author lin.yujiao@whaley.cn
	 */
	public static function getCaculatePaymentInfo($order_id){
		//查询付款信息
		$con = array();
		array_push($con, "order_id ='$order_id'");
		$order_payment_en = M('order_payment') ->
		field("`order_id`,`actual_payment`,`third_order_id`,`payment_amount`,`point_amount`,`cashback_amount`,`freight`")->
		where (join(" AND ",$con) )-> find();
		//$third_order_id = $order_payment_en['third_order_id'];
		//实付金额
		$payment_amount = $order_payment_en['actual_payment'];
		if(empty($payment_amount) || $payment_amount == 0){
			$payment_amount = $order_payment_en['payment_amount'];
		}
		//$point_amount =$order_payment_en['point_amount'];
		$feight_amount = $order_payment_en['freight'];
		//$cashback_amount =$order_payment_en['cashback_amount'];
		//发票金额 = 支付金额 减去 返现金额，积分金额，运费
		$discount_amounts = M('order_discount')->where("order_id='$order_id' AND discount_type IN (3,4,5,6,31,32)")->sum('discount_amount');
		//发票总金额
		$order_payment_en['invoice_amount'] = $payment_amount - $feight_amount- $discount_amounts;
		return $order_payment_en;
	}
	/**
	 * Description: 抽出构造基础的发票数据
	 * @version 2016年12月12日 下午5:15:54 
	 * @author lin.yujiao@whaley.cn
	 * @param unknown $order_id
	 * @param unknown $user
	 */
	private static function fillBaseOrderInvoiceData($order_id, $invoice_type, $user){
		$order_en = M('order_info') -> where("order_id='$order_id'") -> find();
		//查询付款信息并计算发票总金额
		$payment_info = self::getCaculatePaymentInfo($order_id);
		$data = array(
		  'invoice_serial_no' => CommonBiz::getInvoiceSeq(),
		  'invoice_kind' => $invoice_type,
		  'invoice_date' => date("y-m-d H:i:s", time()),
		  'invoice_amount' => $payment_info['invoice_amount'],
		  'invoice_name' => (!empty( $order_en['invoice_title']) ? $order_en['invoice_title'] : ( !empty( $order_en['invoice_name']) ? $order_en['invoice_name'] : '个人' )),
		  'status' => 1,
		  'order_id' => $order_id ,
		  'third_order_id' => $payment_info['third_order_id'],
		  'platform_tid' => $payment_info['third_order_id'],
		  'platform_code' => CommonBiz::getOrderType($order_en['order_type']),
		  'payee_register_no' => C('OrderConfig.payee_register_no'),
		  'create_date' => date("y-m-d H:i:s", time()),
		  'create_user' => $user
		);
		return $data;
	}
	/**
	 * Description: 发票类型获取中文名称用于返回提示
	 * @version 2016年12月15日 下午5:07:02 
	 * @author lin.yujiao@whaley.cn
	 * @param unknown $invoice_type
	 */
	private static function getInvoiceTypeCn($invoice_type){
		switch ($invoice_type) {
			case '21' :
				return '电子发票';
			case '22' :
				return '纸质发票';
			case '23' :
				return '纸质发票转票';
			default :
				return '发票';
		}
	}
	/**
	 * Description: 新增发票信息
	 */
	
	public static function AddOrderInvoice($orderIds, $invoice_type, $user) {
		ini_set('max_execution_time', '0');
		//将拼接的订单号拆成数组方便循环操作
		$array_order_ids = explode(",", $orderIds);
		$success_lst = '';
		$fail_lst = '';
		$split_flag = ',';
		$invoice_type_cn = self::getInvoiceTypeCn($invoice_type);
		foreach ($array_order_ids as $value){
			//构造基础的发票数据
			$data = self::fillBaseOrderInvoiceData($value,$invoice_type, $user);
			/**
			 * 电子发票还需要添加发票明细字段
			 */
			$is_success = false;
			if($invoice_type =='21'){
				$data['invoice_status'] = 2;
				$is_success = self::saveOrderInvoices($value, $data);
			}else if($invoice_type =='22'||$invoice_type =='23'){//纸质发票等
				$data['invoice_status'] = 4;
				$is_success = true;
			}
			if($is_success){
				$today = date("y-m-d H:i:s", time());
				$invoice_status = $data['invoice_status'];
				$Model = new Model();
				$Model->execute("update order_info set invoice_status = " .$invoice_status . " , invoice_date='$today', invoice_kind='$invoice_type'
						where order_id ='$value'");
				$success_lst = ($success_lst . $data['order_id'] . $split_flag);
			}else{
				$fail_lst = ($fail_lst . $data['order_id'] . $split_flag);
			}
		}
		return self::buildInvoceMsg($success_lst, $fail_lst, $invoice_type_cn, $split_flag);
	}
	private static function buildInvoceMsg($success_lst,$fail_lst,$invoice_type_cn,$split_flag){
		$msg = '';
		$success_lst = self::clearLastSplitFlag($success_lst, $split_flag);
		$fail_lst = self::clearLastSplitFlag($fail_lst, $split_flag);
		if(!empty($success_lst)){
			$msg = ($msg . $success_lst .' '. $invoice_type_cn . '申请成功;');
		}
		if(!empty($fail_lst)){
			$msg = ($msg . $fail_lst .' '. $invoice_type_cn . '申请失败;');
		}
		return $msg;
	}
	private static function clearLastSplitFlag($msg,$split_flag){
		$index = strrpos($msg,$split_flag);
		return substr($msg,0,$index);
	}
	/**
	 * 插入OrderInvoiceItem 并回传 税额
	 * @param unknown $thirdOrderId
	 * @param unknown $serial_no
	 */
	public static function saveOrderInvoices($orderId, &$data) {
		ini_set('max_execution_time', '0');
		//根据传入的ID获取订单信息
		$order_en = M('order_info')->where("order_id='$orderId'")->find();
		//获取订单明细以及合计
		$lst_order_detail_en = M('order_detail') -> where("order_id='$orderId'") -> select();
		if(sizeof($lst_order_detail_en) > 0){
			/* $discount_amounts = M('order_discount')
			->where("order_id='$orderId' AND discount_type IN (3,4,5,6,31,32,99)")
			->sum('discount_amount');  */
			//订单总额:sum(payment_amount) from order_detail where order_id=???
			$sum_payment_amount = M('order_detail')->where("order_id ='%s'", $orderId)->sum('payment_amount');
			//折扣金额 = 总额 - 发票金额
			$discount_amounts = ($sum_payment_amount - $data['invoice_amount']);
			//构造发票明细
			$lst_add_invoice_item_en = self::buildOrderInvoiceItem($data['invoice_serial_no'], $order_en, $lst_order_detail_en);
			//发票明细行不为空 构造整体成功情况下 进行后续的折扣构造与数据保存操作
			if(sizeof($lst_add_invoice_item_en) > 0){
				//存在折扣
				if($discount_amounts > 0){
					//invoice新增折扣行，并将折扣算在最贵商品之上，更改其row_type
					$lst_add_invoice_item_en = self::RebuildInvoiceItemList($lst_add_invoice_item_en);
					//构造折扣行数据并放入发票明细航
					$discount_data = self::invoiceData4Dsicount($data['invoice_serial_no'], $discount_amounts, $order_en, $lst_add_invoice_item_en);
					array_push($lst_add_invoice_item_en, $discount_data);
				}
				
				//写入invoice_item
				foreach($lst_add_invoice_item_en as $add_invoice_item_en){
					M('order_invoice_item')->add($add_invoice_item_en);
				}
				
				//计算总数并赋值
				$totalFee  = self::getTotalTaxSumPrice($lst_add_invoice_item_en);
				$data['sum_price'] = $totalFee['totalPrice'];
				$data['sum_tax'] = $totalFee['totalTax'];
				$data['invoice_type'] = 'blue';
				//return $totoalFee;
				$invoice_amount = $data['sum_price'] + $data['sum_tax'];
				$Model = new Model();
				$Model->execute("update order_info set invoice_amount ='$invoice_amount'
						where order_id ='$orderId'");
				//将之前所有票据类型改成无效 应用于冲红票使用
				$Model->execute("update order_invoice set status = 0,red_flag = 1 where order_id ='$orderId'");
				M('order_invoice')->data($data)->add();
				return true;
			}
		}
		return false;
	}
	/**
	 * Description: 抽出构造折扣信息的语句
	 * @version 2016年12月12日 下午7:16:20 
	 * @author lin.yujiao@whaley.cn
	 */
	private static function invoiceData4Dsicount($serial_no, $discount_amounts, $order_en, $lst_add_invoice_item_en){
		$max_invoice_item_en = self::getMaxInvoiceAmountForInvoiceItemList($lst_add_invoice_item_en) ;
		//折扣税率
		$discount_tax_rate = $max_invoice_item_en['tax_rate'];
		$invoice_itm_max = $max_invoice_item_en['invoice_amount'];
		$data['invoice_serial_no'] = $serial_no;
		$data['order_id'] = $order_en['order_id'];
		$data['third_order_id'] = $order_en['third_order_id'];
		$data['tax_rate'] = $discount_tax_rate;
		$data['invoice_amount'] =  $discount_amounts;
		$data['item_name'] = '折扣('.sprintf("%01.3f",round($discount_amounts * 100 / $invoice_itm_max,3)).'%)';
		//减去会员包之后算出来不含税价格
		$data['sum_price'] = self::chargeTaxByRate($discount_amounts, $data['tax_rate']) ;
		//不含会员包的税额
		$data['tax'] = ($discount_amounts - $data['sum_price']);
		$data['row_type'] = 1;
		$data['invoice_amount'] = 0 - $data['invoice_amount'];
		$data['sum_price'] = 0 - $data['sum_price'];
		$data['tax'] = 0 - $data['tax'];
		return $data;
	}
	/**
	 * 
	 * @param unknown $price
	 * @param  $rate 例如 0.17
	 */
	public static function chargeTaxByRate($price,$rate){
		$rate_charge = 1.0 + floatval($rate);
		return round(($price / $rate_charge),2);
	}
	/**
	 * 小数点后6位的不含税单价
	 * @param unknown $price
	 * @param unknown $rate
	 */
	public static function chargePriceByRate($price,$rate){
		$rate_charge = 1.0 + floatval($rate);
		return round(($price / $rate_charge),6);
	}
	/**
	 * Description: 获取VIP会员服务
	 * @version 2016年11月8日 下午2:51:44
	 * @author lin.yujiao@whaley.cn
	 */
	public static function getVipBagLst(){
		$lst_result;
		$lst_vip_bag = M ( 'product_split', '', 'DB_whaley_product' )->where("is_vip_bag = 1")->select();
		foreach($lst_vip_bag as $vip_bag){
			$lst_result[$vip_bag['id']] = $vip_bag;
		}
		return $lst_result;
	}
	/**
	 * Description: 获取数组中对应sku_id信息的PRODUCT_SPLIT配置数据
	 * @version 2016年12月13日 下午3:56:11 
	 * @author lin.yujiao@whaley.cn
	 * @param unknown $array_lst
	 * @param unknown $key
	 */
	public static function getProductSplitBySkuIds($array_lst,$key){
		//循环获取列表中的sku值信息
		$sku_ids = array();
		foreach($array_lst as $item){
			array_push($sku_ids, $item[$key]);
		}
		//在相应product_split表中取出相应的sku配置数据
		$lst_result;
		$condition_array['sku_id'] = array('IN',$sku_ids);
		$condition_array['is_vip_bag'] = array('eq',0);
		$lst_prd_split = M ( 'product_split', '', 'DB_whaley_product' )->where($condition_array)->select();
		foreach($lst_prd_split as $prd_itm){
			$lst_result[$prd_itm['sku_id']] = $prd_itm;
		}
		return $lst_result;
	}
	/**
	 * Description: 构造发票明细数据
	 * @version 2016年12月13日 下午4:51:26 
	 * @author lin.yujiao@whaley.cn
	 */
	public function buildOrderInvoiceItem($serial_no, $order_en, $lst_order_detail_en){
		//获取VIP会员服务并映射成K-V格式
		$vip_bag_lst = self::getVipBagLst();
		$lst_prd_split = self::getProductSplitBySkuIds($lst_order_detail_en, 'third_sku_id');
		$lst_add_invoice_item_en = array();
		foreach($lst_order_detail_en as $order_detail_en){
			//是否在配置信息中存在数据
			if($lst_prd_split[$order_detail_en['third_sku_id']] != null){
				//支付金额大于0的情况进行开票
				if($order_detail_en['payment_amount'] > 0){
					//获取配置列拆分后的数组
					$prd_split_info = $lst_prd_split[$order_detail_en['third_sku_id']];
					//会员包价格 根据配置信息判断该产品有没有配置会员包 若配置取出相应会员包的售价
					$vip_bag_info = $vip_bag_lst[$prd_split_info['referent_id']];
					//取出会员包的含税价格 便于下一步计算
					$vipBagAmount = floatval( empty($vip_bag_info) ? 0 : $vip_bag_info['sale_amount'] );
					//构造产品的发票明细航
					$dataTv = self::buildDataTv($serial_no, $vipBagAmount, $order_detail_en, $prd_split_info);
					
					array_push($lst_add_invoice_item_en, $dataTv);
					
					//存在会员包信息或者会员包价格大于0 需要包装会员包明细数据
					if($vipBagAmount > 0){
						$dataVipBag = self::buildDataVipBag($serial_no, $vipBagAmount,$vip_bag_info, $order_detail_en);
							
						array_push($lst_add_invoice_item_en, $dataVipBag);
					}
				}
			}else{
				//若未找到则终止该发票的构造和存储 返回空数据由上层继续下一张发票的构造
				return array();
			}
		}
		return $lst_add_invoice_item_en;
	}
	/**
	 * Description: 构造产品的发票明细行
	 * @version 2016年12月13日 下午4:49:28 
	 * @author lin.yujiao@whaley.cn
	 */
	private function buildDataTv($serial_no, $vipBagAmount, $order_detail_en, $prd_split_info){
		//用户支付金额
		$total_payment_amount = $order_detail_en['payment_amount'];
		//减去会员包后的支付金额
		$total_payment_amount_no_vipBag = $total_payment_amount -($vipBagAmount * $order_detail_en['qty']);
		//减去VIP会员包之后的单件商品的价格
		$sigle_amount_no_vipBag = $total_payment_amount_no_vipBag / $order_detail_en['qty'];
		//包装电视机 发票明细信息
		$dataTv['invoice_serial_no'] = $serial_no;
		$dataTv['order_id'] = $order_detail_en['order_id'];
		$dataTv['third_order_id'] = $order_detail_en['third_order_id'];
		$dataTv['tax_rate'] = $prd_split_info['tax'];
		$dataTv['item_name'] = $prd_split_info['invoice_title'];
		//减去会员包之后算出来不含税价格
		$dataTv['sum_price'] = self::chargeTaxByRate($total_payment_amount_no_vipBag, $dataTv['tax_rate']) ;
		//不含会员包的税额
		$dataTv['tax'] = $total_payment_amount_no_vipBag - $dataTv['sum_price'];
		//含税总价
		$dataTv['invoice_amount'] =  $total_payment_amount_no_vipBag;
		$dataTv['row_type'] = 0;
		$dataTv['item_no'] = $prd_split_info['sku_id'];
		//price是不含税价格
		$dataTv['price'] = self::chargePriceByRate($sigle_amount_no_vipBag, $dataTv['tax_rate']) ;
		$dataTv['amount'] = $sigle_amount_no_vipBag;
		$dataTv['quantity'] =  $order_detail_en['qty'];
		$dataTv['unit']= $prd_split_info['unit'];
		$dataTv['specification']= $prd_split_info['product_size'];
		return $dataTv;
	}
	/**
	 * Description: 构造会员包的发票明细行
	 * @version 2016年12月13日 下午4:49:44 
	 * @author lin.yujiao@whaley.cn
	 */
	private function buildDataVipBag($serial_no, $vipBagAmount,$vip_bag_info, $order_detail_en){
		//包装会员包发票明细信息 如果没有会员包,就不会整
		$dataVipBag['invoice_serial_no'] = $serial_no;
		$dataVipBag['order_id'] = $order_detail_en['order_id'];
		$dataVipBag['third_order_id'] = $order_detail_en['third_order_id'];
		$dataVipBag['item_name'] = $vip_bag_info['invoice_title'];
		$dataVipBag['invoice_amount'] =  $vipBagAmount *  $order_detail_en['qty'];
		$dataVipBag['tax_rate'] = $vip_bag_info['tax'];
		$dataVipBag['sum_price'] = self::chargeTaxByRate($dataVipBag['invoice_amount'], $dataVipBag['tax_rate']);
		$dataVipBag['tax'] =  $dataVipBag['invoice_amount'] - $dataVipBag['sum_price'];
		$dataVipBag['row_type'] = 0;
		$dataVipBag['price'] =  self::chargePriceByRate($vipBagAmount, $dataVipBag['tax_rate']);
		$dataVipBag['amount'] = $vipBagAmount;
		$dataVipBag['quantity'] = $order_detail_en['qty'];
		$dataVipBag['unit']= $vip_bag_info['unit'];
		return $dataVipBag;
	}
	
	public static function paperInvItm4Export($common_info,$qty,$amount,$discount_amounts,$prd_split_info){
		return array(
				$common_info['id'], //订单号
				$common_info['title'],//发票抬头
				'','','',//税号 -  地址 -  电话
				$prd_split_info['invoice_title'],//商品名称
				$prd_split_info['product_size'],//规格型号
				$prd_split_info['unit'],//商品单位
				$qty,//商品数量
				$amount, //商品金额
				$prd_split_info['tax'],//税率
				$discount_amounts,//折扣金额
				'',//快递单号
				$common_info['consignee_name'],//收件人姓名
				$common_info['consignee_cellphone'],//收件人手机
				$common_info['address'],//收件人地址
				$common_info['consignee_zip']//邮编
		);
	}
	
	public function RebuildInvoiceItemList($lst_invoice_item_en){
		 
		$key_Max_Index = '';
		$max_amount = 0;
	
		foreach($lst_invoice_item_en as $key=>$invoice_item_en){
			if($invoice_item_en['invoice_amount'] > $max_amount){
				$max_amount = $invoice_item_en['invoice_amount'];
				$key_Max_Index = $key;
			}
		}
		 
		$lst_invoice_item_en[$key_Max_Index]['row_type'] = '2';
		 
		return $lst_invoice_item_en;
	}
	
	/**
	 * 获得最贵的invoice_item
	 */
	public function getMaxInvoiceAmountForInvoiceItemList($lst_invoice_item_en){
	
		$key_Max_Index = '';
		$max_amount = 0;
		foreach($lst_invoice_item_en as $key=>$invoice_item_en){
			if($invoice_item_en['invoice_amount'] > $max_amount){
				$max_amount = $invoice_item_en['invoice_amount'];
				$key_Max_Index = $key;
			}
		}
		return $lst_invoice_item_en[$key_Max_Index];
	}
	
   public static function getTotalTaxSumPrice($lst_add_invoice_item_en){

   				$allTaxFee=0;
   				$allSumPrice=0;

   				foreach ($lst_add_invoice_item_en as $invoice_item_en){
   					
   						$allTaxFee = $allTaxFee +$invoice_item_en['tax'];
   						$allSumPrice=$allSumPrice +$invoice_item_en['sum_price'];
   				}
   				
   				$total =array(
   						'totalTax'   => $allTaxFee,
   						'totalPrice'  => $allSumPrice,
   				);
   				return $total;
   }
   
   
   public static function changeInvoiceKind($thirdOrderId,$invoiceKind){
   	
   	$Model = new Model();
   	
   	$Model->execute("update order_info set invoice_kind = $invoiceKind where third_order_id ='$thirdOrderId'");
   
   }
   /**
    * Description: 填充EXCEL表头TITLE
    * @version 2016年9月2日 下午3:05:49 
    * @author lin.yujiao@whaley.cn
    * @param array $table_header_array
    * @param string $title
    */
   private function fillExcelHeader($table_header_array,$title){
   	$objPHPExcel = new  \PHPExcel();
   	$objPHPExcel->setActiveSheetIndex(0);
   	$objPHPExcel->getActiveSheet()->setTitle($title);
   	//表头字母
   	$header_letter_array = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X');
   	//设置表头(第一行)
   	$row_index = 1;
   	foreach($header_letter_array as $header_letter){
   		$table_row_index = $row_index - 1;
   		$objPHPExcel->getActiveSheet()->setCellValue($header_letter.strval(1),
   				$table_header_array[$table_row_index]);
   		$objPHPExcel->getActiveSheet()->getStyle($header_letter.strval(1))->getFont()->setBold(true);
   	
   		$row_index = $row_index + 1;
   	}
   	return $objPHPExcel;
   }
   /**
    * Description: 返利计提excel导出
    * @version 2016年9月2日 下午2:57:39 
    * @author lin.yujiao@whaley.cn
    * @param unknown $params_en
    */
   public static function rebateAccruedExcel(){
   	Vendor('phpExcel.PHPExcel');
   	//表头设置start
   	$table_header_array = array(
   			'客户代码',
   			'客户名称',
   			'产品型号',
   			'数量(台)',
   			'实际成交单价(￥)',
   			'实际成交总价(￥)',
   			'返利比例',
   			'返利金额'
   	);
   	//表头设置end
   	$objPHPExcel = OrderBiz::fillExcelHeader($table_header_array, '导出返利计提信息');
   
   	// 搜索条件start
   	$condition_array = array();
   	//经销商类型
   	array_push($condition_array, "o.order_type = 8");
   	//已完成订单
   	array_push($condition_array, "o.order_status = 35");
   	// 搜索条件end
   
   
   	//订单信息
   	$condition_sql = implode(' AND ', $condition_array);
   
   	$lst_rrsStockOrder_en = 
   		M('order_info')->alias('o')->
   		where($condition_sql)-> 
	   	Field("d.`k3_code` AS 'k3_code',d.`dealer_name` AS 'dealer_name',od.`sku_name` AS 'sku_name',
	   		   COUNT(1) AS 'coun',od.`goods_payment_amount` AS 'goods_payment_amount',
	  		   SUM(od.`payment_amount`) AS 'payment_amount',d.`discount_rate`,
	   		   CONCAT(ROUND(d.`discount_rate` *100,0),'%') AS 'discount_rate',
	   		   SUM(od.`discount_fee`) AS 'discount_fee'")->
	   	join("order_detail od  ON o.order_id = od.order_id ")->
	   	join("dealer_info d  ON d.dealer_id = o.buyer_alipay_no ")->
	   	group('d.`k3_code`,
	   		   d.`dealer_name`,
	   		   od.`sku_id`,
	   		   od.sku_name,
	  		   od.`goods_payment_amount`')->
   		order("d.k3_code")->
   	select();
   	// 	 return  M('')->getLastSql();
   	//xls数据拼接start
   	//行号，从第二行起
   	$row_num = 2;
   	foreach($lst_rrsStockOrder_en as $order_en){
   
   		//客户代码
   		$objPHPExcel->getActiveSheet()->setCellValue('A'.strval($row_num),
   				$order_en['k3_code']);
   
   		//客户名称
   		$objPHPExcel->getActiveSheet()->setCellValue('B'.strval($row_num),
   				$order_en['dealer_name']);
   
   		//产品型号
   		$objPHPExcel->getActiveSheet()->setCellValue('C'.strval($row_num),
   				$order_en['sku_name']);
   
   		//数量(台)
   		$objPHPExcel->getActiveSheet()->setCellValue('D'.strval($row_num),
   				$order_en['coun']);
   
   		//实际成交单价(￥)
   		$objPHPExcel->getActiveSheet()->setCellValue('E'.strval($row_num),
   				$order_en['goods_payment_amount']);
   
   		//实际成交总价(￥)
   		$objPHPExcel->getActiveSheet()->setCellValue('F'.strval($row_num),
   				$order_en['payment_amount']);
   
   		//返利比例
   		$objPHPExcel->getActiveSheet()->setCellValue('G'.strval($row_num),
   				$order_en['discount_rate']);
   		
   		//返利金额
   		$objPHPExcel->getActiveSheet()->setCellValue('H'.strval($row_num),
   				$order_en['discount_fee']);
   			
   		$row_num = $row_num + 1;
   	}
   	//xls数据拼接end
   
   	return $objPHPExcel;
   }





    /**
     * ================  Submit Order相关 Begin  ================
     */


    /**
     * 校验订单数据
     */
    public static function VerifyOrder(){

    }



    /**
     * 计算购物车商品金额
     * 运用促销规则
     * 计算运费（暂无）
     * 并返回购物车商品明细(包括金额运费促销数量等)
     */
    public static function calcCart($lst_sku_str, $sku_channel){

        $goods_amount		= 0;
        $goods_qty		    = 0;
        $promotion_amount	= 0;
        $freight            = 0;
        $no_freight_order_amount  = 0;
        $order_amount       = 0;


        // ============= 计算sku金额和数量 begin =============
        $lst_param_sku = array();
        $lst_buy_sku_id = array();
        $lst_sku_str_array = explode('|', $lst_sku_str);
        foreach($lst_sku_str_array as $sku_str){
            $sku_str_array = explode(',', $sku_str);
            $sku = array(
                'sku_id'=> $sku_str_array[0],
                'qty'	=> $sku_str_array[1],
                'payment_price'    => $sku_str_array[2],
            );
            array_push($lst_param_sku, $sku);
            array_push($lst_buy_sku_id, $sku['sku_id']);
        }

        $lst_sku_en = M('sku', '', 'DB_whaley_product')
            ->where("sku_channel = ".$sku_channel." AND status = 1 AND sku_id IN('".implode("','", $lst_buy_sku_id)."')")
            ->select();

        foreach($lst_sku_en as $key => $sku_en){
            $curr_sku_id = $sku_en['sku_id'];

            $lst_filter_param_sku = array_filter($lst_param_sku,
                function($item) use ($curr_sku_id) {
                    return $item['sku_id'] == $curr_sku_id;
                });
            if(empty($lst_filter_param_sku)){
                continue;
            }
            $curr_sku_en   			    = current($lst_filter_param_sku);
            $lst_sku_en[$key]['qty']    = $curr_sku_en['qty'];
            $lst_sku_en[$key]['payment_price']  = $curr_sku_en['payment_price'];


            $lst_sku_en[$key]['image']  = C('UriConfig.sku_image_450_pre_url').$lst_sku_en[$key]['image'];
            $goods_amount         	    = $goods_amount + $sku_en['sale_price'] * $curr_sku_en['qty'];
            $goods_qty			        = $goods_qty + $curr_sku_en['qty'];
        }
        // ============= 计算sku金额和数量 end =============


        // ============= 【无】计算促销金额 begin =============
//        $lst_promotion_en   = M('promotion','','DB_whaley_product')
//            ->where('promotion_channel=5 AND promotion_type=1 AND status=1')->order('discount_amount DESC')
//            ->select();
//
//
//        $curr_promotion_en   = null;
//        foreach($lst_promotion_en as $promotion_en){
//            $promotion_sku_amount   = 0;
//            foreach($lst_sku_en as $sku_en){
//                $curr_sku_id    = $sku_en['sku_id'];
//
//                //判断当前sku是否支持促销
//                $str_select_flag= strstr($promotion_en['sku_id_list'], $curr_sku_id);
//                if(empty($promotion_en['sku_id_list'])){
//                    $str_select_flag = true;
//                }
//
//                if(!empty($str_select_flag)){
//                    $promotion_sku_amount   = $promotion_sku_amount + intval($sku_en['qty']) * floatval($sku_en['sale_price']);
//                }
//            }
//
//            //判断是否满足满减条件
//            if($promotion_sku_amount >= $promotion_en['condition_amount']) {
//                $curr_promotion_en = $promotion_en;
//                break;
//            }
//        }
//        if(!empty($curr_promotion_en)){
//            $promotion_amount = $curr_promotion_en['discount_amount'];
//        }
        // ============= 【无】计算促销金额 end =============


        // ============= 计算运费金额 begin =============
        $freight    = 0;
        // ============= 计算运费金额 end =============


        // ============= 计算订单金额 begin =============
        $no_freight_order_amount  = $goods_amount - $promotion_amount;
        $order_amount       = $no_freight_order_amount + $freight;
        // ============= 计算订单金额 end =============

        $return_array   = array(
            'goods_qty'     => $goods_qty,
            'goods_amount'  => $goods_amount,
            'promotion_en'  => null,
            'promotion_amount'  => $promotion_amount,
            'freight'           => $freight,
            'no_freight_order_amount'=> $no_freight_order_amount,
            'order_amount'  => $order_amount,
            'lst_sku_en'    => $lst_sku_en
        );

        return $return_array;
    }

    /**
     * ================  Submit Order相关 Begin  ================
     */
}